<template>
  <el-container class="add-friend-container">
    <el-header>
      <el-button type="text" @click="goBack">返回好友列表</el-button>
    </el-header>
    <el-main>
      <el-input v-model="searchUserId" placeholder="输入用户ID" />
      <el-button type="primary" @click="searchUser">查找</el-button>
      <div v-if="user" class="user-info">
        <el-avatar :src="user.avatar || defaultAvatar" size="large" />
        <div class="user-details">
          <p>{{ user.username }}</p>
          <el-tag :type="user.status === 'online' ? 'success' : 'info'">
            {{ user.status === 'online' ? '在线' : '离线' }}
          </el-tag>
        </div>
        <el-button type="primary" @click="addFriend">添加好友</el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { defaultAvatar } from '@/assets/defaultAvatar';

interface User {
  id: string;
  username: string;
  avatar?: string;
  status: 'online' | 'offline';
}

const router = useRouter();
const searchUserId = ref('');
const user = ref<User | null>(null);

const searchUser = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/users/${searchUserId.value}`);
    user.value = response.data;
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '查找用户失败');
  }
};

const addFriend = async () => {
  try {
    const userId = localStorage.getItem('userId');
    await axios.post(`${API_BASE_URL}/${userId}/friends`, {
      friendId: searchUserId.value
    });
    ElMessage.success('添加好友成功');
    router.push('/friends');
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '添加好友失败');
  }
};

const goBack = () => {
  router.push('/friends');
};
</script>

<style scoped>
.add-friend-container {
  width: 100%;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

.user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}
</style> 